package com.hkfrich.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkfrich.common.constant.Constants;
import com.hkfrich.common.exception.UserException;
import com.hkfrich.common.utils.JwtUtils;
import com.hkfrich.common.utils.ResultUtils;
import com.hkfrich.common.utils.SecurityUtils;
import com.hkfrich.common.utils.StringUtils;
import com.hkfrich.framework.config.HKFRichAPIConfig;
import com.hkfrich.redis.RedisUtils;
import com.hkfrich.system.domain.SysRole;
import com.hkfrich.system.domain.SysUser;
import com.hkfrich.system.domain.SysUserRole;
import com.hkfrich.system.mapper.SysRoleMapper;
import com.hkfrich.system.mapper.SysUserMapper;
import com.hkfrich.system.mapper.SysUserRoleMapper;
import com.hkfrich.system.security.domain.SecurityUserDetails;
import com.hkfrich.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName UserServiceImpl
 * @Desscription
 * @Author _HeiShuai
 * @Date 2022/8/18 14:57
 * @Version 1.0
 **/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private HKFRichAPIConfig hkfRichAPIConfig;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;


    @Override
    public ResultUtils login(SysUser user) {
        //验证码开关
        Boolean captchaEnable = hkfRichAPIConfig.getCaptchaEnable();
        if (captchaEnable) {
            String authCode = RedisUtils.getValue(Constants.CAPTCHA_CODE_KEY + user.getUserName())+"";
            if (!(user.getAuthCode().equals(authCode))) {
                throw new UserException("验证码不正确或已失效");
            }
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new UserException("用户名或密码错误");
        }
        SecurityUserDetails securityUserDetails = (SecurityUserDetails) authenticate.getPrincipal();
        if (securityUserDetails.getSysUser().getStatus().equals(Constants.STATUS_DISABLE)){
            throw new UserException("账户已经锁定，请联系管理员");
        }
        SysUser sysUser = securityUserDetails.getSysUser();
        String userName = sysUser.getUserName();
        String jwt = JwtUtils.createJWT(userName);
        //存用户信息
        RedisUtils.setValue(Constants.USERINFO + userName, securityUserDetails);
        // 角色集合
        List<SysRole> roles = securityUserDetails.getSysUser().getRoles();
        // 权限集合
        List<String> permissions = securityUserDetails.getPermissions();
        Map<String, Object> map = new HashMap<>(1);
        map.put("token", jwt);
        map.put("userInfo", sysUser);
        map.put("roles", roles);
        map.put("permissions", permissions);
        return ResultUtils.success(map, "登陆成功");
    }

    @Override
    public ResultUtils logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SecurityUserDetails securityUserDetails = (SecurityUserDetails) authentication.getPrincipal();
        String userName = securityUserDetails.getSysUser().getUserName();
        RedisUtils.deleteObject(Constants.USERINFO + userName);
        return ResultUtils.success("退出成功");
    }

    @Override
    public SysUser selectUserVoById(SysUser sysUser) {
        return sysUserMapper.selectUserVoById(sysUser);
    }

    @Override
    public SysUser selectUserVoByUserName(String userName) {
        return sysUserMapper.selectUserVoByUserName(userName);
    }


    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = sysUserMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return Constants.NOT_UNIQUE;
        }
        return Constants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = sysUserMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return Constants.NOT_UNIQUE;
        }
        return Constants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = sysUserMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return Constants.NOT_UNIQUE;
        }
        return Constants.UNIQUE;
    }

    @Override
    public Map selectUserAndRoles(SysUser sysUser) {
        Map<String, Object> map = new HashMap<>();
        LambdaQueryWrapper<SysRole> query = Wrappers.lambdaQuery(SysRole.class);
        query.ne(SysRole::getDelFlag,Constants.DEL_FLAG_VALUE);
        List<SysRole> roles = sysRoleMapper.selectList(query);
        if(StringUtils.isNotNull(sysUser.getUserId())){
            SysUser user = sysUserMapper.selectUserVoById(sysUser);
            map.put("userInfo", user);
            map.put("roleIds", user.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        map.put("roles",SysUser.isAdmin()?roles:roles.stream().filter(r -> !Constants.ADMIN_ROLE.equals(r.getRoleKey())).collect(Collectors.toList()));
        return map;
    }


}
